package com.bxs.detector;

import com.bxs.detector.impl.*;
import com.bxs.pojo.DangerMsg;
import com.bxs.pojo.BaseRule;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.pcap4j.core.PcapPacket;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class DetectorEngine {
    // 一组检测器
    List<BaseDetector> detectorList = new ArrayList<>();

    // 检测规则（动态加载）
    protected List<BaseRule> rules = new ArrayList<>();

    //开始检测
    public DangerMsg execute(PcapPacket packet){
        for(BaseDetector detector : detectorList){
            DangerMsg res = null;
            try {
                res = detector.detect(packet, rules);
            } catch (JsonProcessingException e) {
                log.error(e.getMessage(), e);
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage(), e);
            }
            System.out.println("detect res: " + (res == null));
            if (res != null) {
                // 存在威胁
                System.out.println("检测到威胁，进行日志记录");
                // 记录日志
                return res;
            }
        }
        return null;
    }

    // 自动装配支持的检测器
    public void autoConfigureDetector(){
        // IP 报文检测器
        register(new IpPacketDetector());
        // ICMP报文检测器
        register(new ICMPPacketDetector());
        // TCP报文检测器
        register(new TcpPacketDetector());
        // UDP报文检测器
        register(new UDPPacketDetector());
        // http报文检测器
        register(new HttpPacketDetector());
    }


    public void register(BaseDetector detector){detectorList.add(detector);}

    public void registerRule(BaseRule rule){rules.add(rule);}

    public void setRules(List<BaseRule> rules){
        this.rules = rules;
    }
}
